#!/bin/bash

# Stop on error
set -e
# Echo all commands to Travis log
set -x

mkdir build-travis build32 build-sparse build-aarch64

# Build with latest clang first
cd build-travis
CC=clang-5.0 CFLAGS=-Werror cmake -GNinja .. -DIOCTL_MODE=both
ninja
../buildlib/check-build --src .. --cc clang-5.0

# 32 bit build to check format strings/etc
cd ../build32
# travis's trusty is not configured in a way that enables all 32 bit
# packages. We could fix this with some sudo stuff.. For now turn off libnl
CC=gcc-7 CFLAGS="-Werror -m32" cmake -GNinja .. -DENABLE_RESOLVE_NEIGH=0 -DIOCTL_MODE=both
ninja

# aarch64 build to check compilation on ARM 64bit platform
cd ../build-aarch64
CC=$HOME/aarch64/bin/aarch64-linux-gnu-gcc CFLAGS="-Werror -Wno-maybe-uninitialized" cmake -GNinja .. -DENABLE_RESOLVE_NEIGH=0 -DIOCTL_MODE=ioctl
ninja

# Run sparse on the subdirectories which are sparse clean
cd ../build-sparse
mv ../CMakeLists.txt ../CMakeLists-orig.txt
grep -v "# NO SPARSE" ../CMakeLists-orig.txt > ../CMakeLists.txt
CC=cgcc CFLAGS="-Werror" cmake -GNinja .. -DIOCTL_MODE=both
ninja | grep -v '^\[' | tee out
# sparse does not fail gcc on messages
if [ -s out ]; then
   false
fi
mv ../CMakeLists-orig.txt ../CMakeLists.txt

# Test with coherent DMA mode disabled (ie as would be on ARM32, etc)
cd ../build-travis
cp ../util/udma_barrier.h ../util/udma_barrier.h.old
echo "#error Fail" >> ../util/udma_barrier.h
rm CMakeCache.txt
CC=clang-5.0 CFLAGS=-Werror cmake -GNinja .. -DIOCTL_MODE=both
ninja
cp ../util/udma_barrier.h.old ../util/udma_barrier.h

# Finally run through gcc-7 64 bit through the debian packaging This gives a
# good clue if patches are changing packaging related things, the RPM stuff
# will have to be audited by hand.

# When running cmake through debian/rules it is hard to set -Werror,
# instead force it on by changing the CMakeLists.txt
cd ..
echo 'set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")' >> buildlib/RDMA_EnableCStd.cmake
sed -i -e 's/-DCMAKE_BUILD_TYPE=Release//g' debian/rules
sed -i -e 's/ninja \(.*\)-v/ninja \1/g' debian/rules

CC=gcc-7 debian/rules build
fakeroot debian/rules binary
